import {
  ApiResponse,
  QueryRequest,
  QueryResponse,
  ChartConfigRequest
} from '../types';


const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000';

async function fetchApi<T>(
  endpoint: string,
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
  body?: any
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`;
  
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
  };
  
  const options: RequestInit = {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  };
  
  try {
    const response = await fetch(url, options);
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.detail || `API请求失败: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
}

export async function processQuery(query: string): Promise<QueryResponse> {
  const request: QueryRequest = { query };
  return fetchApi<QueryResponse>('/api/query', 'POST', request);
}

export async function generateChartConfig(
  data: any[],
  query: string,
  chartType?: string
): Promise<any> {
  const request: ChartConfigRequest = {
    data,
    query,
    chart_type: chartType
  };
  return fetchApi<any>('/api/chart', 'POST', request);
}